import { useState, useEffect, useCallback } from 'react';

const useTimer = () => {
    const [time, setTime] = useState(() => {
        // 从 localStorage 获取已存储的时间
        return parseInt(localStorage.getItem('practiceTime')) || 0;
    });
    const [isRunning, setIsRunning] = useState(false);

    // 开始计时
    const startTimer = useCallback(() => {
        // 不再重置时间，而是继续从当前时间开始
        setIsRunning(true);
    }, []);

    // 停止计时
    const stopTimer = useCallback(() => {
        setIsRunning(false);
        // 保存时间到临时存储
        localStorage.setItem('practiceTime', time.toString());
    }, [time]);

    // 格式化时间
    const formatTime = useCallback((seconds) => {
        const hours = Math.floor(seconds / 3600);
        const minutes = Math.floor((seconds % 3600) / 60);
        const remainingSeconds = seconds % 60;

        return {
            hours,
            minutes,
            seconds: remainingSeconds,
            formatted: `${hours.toString().padStart(2, '0')}:${minutes
                .toString()
                .padStart(2, '0')}:${remainingSeconds.toString().padStart(2, '0')}`
        };
    }, []);

    // 自动保存时间
    useEffect(() => {
        if (time > 0) {
            localStorage.setItem('practiceTime', time.toString());
        }
    }, [time]);

    useEffect(() => {
        let intervalId;

        if (isRunning) {
            intervalId = setInterval(() => {
                setTime(prevTime => prevTime + 1);
            }, 1000);
        }

        return () => {
            if (intervalId) {
                clearInterval(intervalId);
            }
        };
    }, [isRunning]);

    return {
        time,
        isRunning,
        startTimer,
        stopTimer,
        formatTime
    };
};

export default useTimer; 